package com.test.thread;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SampleThread extends Thread {

	public Object l;

	private int count = 0;
	private static int tc = 0;

	// private volatile double d = 0;

	public SampleThread(int priority, Object l) {
		super("" + ++tc);
		this.l = l;
		if (Thread.MAX_PRIORITY == priority) {
			setDaemon(true);
		}
		setPriority(priority);
		this.start();
	}

	public void run() {
		while (count++ < 500) {
			System.out.println(this.toString() + ": " + count);
			try {
				sleep(5000);
			} catch (InterruptedException e) {
				System.out.println(this.toString() + ": " + count + " InterruptedException");
				e.printStackTrace();
				// return;
			}
		}

	}

	public void myWait() {
		try {
			synchronized (l) {
				l.wait();
			}
		} catch (InterruptedException e) {
			System.out.println("myWait InterruptedException");
		}
	}

	public void myNotify() {
		l.notify();
	}

	public String toString() {
		return "#" + this.getName() + " - " + this.getPriority();
	}

	public static void main(String[] args) {
		try {
			Object l = new Object();
			SampleThread[] ts = new SampleThread[3];
			ts[0] = new SampleThread(Thread.MAX_PRIORITY, l);
			ts[1] = new SampleThread(5, l);
			ts[2] = new SampleThread(5, l);
			String act = "";
			System.out.println("Please input command:q--quit,l--list,i--interrupt>");
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

			while (true) {
				act = br.readLine();
				System.out.println(act);
				if ("q".equals(act)) {
					System.out.println("I am quiting...");
					System.exit(0);
				}
				if ("l".equals(act)) {
					System.out.println("Running threads total:" + ts.length + ",are:");
					for (int i = 0; i < ts.length; i++) {
						System.out.println(ts[i].getName() + "-" + ts[i].getPriority() + "-" + ts[i].isAlive() + "-" + ts[i].isDaemon());
					}
				}
				if ("i".equals(act)) {
					ts[0].interrupt();
				}
				if ("w".equals(act)) {
					System.out.println("---");
					ts[0].myWait();
				}
				if ("n".equals(act)) {
					ts[0].myNotify();
				}
			}
			// sleep(5000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
